package com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.permissions

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager.widget.PagerAdapter
import androidx.viewpager.widget.ViewPager
import com.helasasa.maxfunds.lineofcredit.cashloan.ProjectApplication
import com.helasasa.maxfunds.lineofcredit.cashloan.R
import com.helasasa.maxfunds.lineofcredit.cashloan.databinding.ActivityGhanaPermissionBinding
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.http.hitPoint
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.permissions.subview.IPermissionGhanaAskDialogListener
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.permissions.subview.PermissionGhanaAskDialog
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.subview.HotlineGhanaDialog
import com.vmadalin.easypermissions.EasyPermissions
import com.vmadalin.easypermissions.dialogs.DEFAULT_SETTINGS_REQ_CODE
import com.vmadalin.easypermissions.dialogs.SettingsDialog

class PermissionGhanaSplashActivity : AppCompatActivity(), EasyPermissions.PermissionCallbacks,
    EasyPermissions.RationaleCallbacks {

    private lateinit var permissionViewModel: PermissionGhanaSplashViewModel
    private lateinit var binding: ActivityGhanaPermissionBinding
    private lateinit var askDialog: PermissionGhanaAskDialog
    private lateinit var indicatorAdapter: PermissionGhanaSplashIndicatorAdapter
    private lateinit var pageAdapter: PermissionGhanaSplashPageAdapter

    @SuppressLint("NotifyDataSetChanged", "SetTextI18n")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // 数据模型
        permissionViewModel = ViewModelProvider(this)[PermissionGhanaSplashViewModel::class.java]

        // 关联布局
        binding = ActivityGhanaPermissionBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // 用到的控件
        val back = binding.navbarLeft
        val hotline = binding.navbarRight
        val loading = binding.loading
        val indicatorList = binding.indicatorList
        val viewPager = binding.viewPager
        val checkbox = binding.checkbox

        // 初始化indicator
        indicatorAdapter = PermissionGhanaSplashIndicatorAdapter(permissionViewModel.pagerDataList)
        indicatorList.layoutManager =
            LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
        indicatorList.adapter = indicatorAdapter

        // 初始化viewpager
        pageAdapter = PermissionGhanaSplashPageAdapter(this, permissionViewModel.pagerDataList)
        viewPager.pageMargin = 0
        viewPager.offscreenPageLimit = 3
        viewPager.addOnPageChangeListener(
            object : ViewPager.OnPageChangeListener {
                override fun onPageScrolled(
                    position: Int,
                    positionOffset: Float,
                    positionOffsetPixels: Int
                ) {
                }

                override fun onPageSelected(position: Int) {
                    for (index in 0 until permissionViewModel.indicatorDataList.size) {
                        val item = permissionViewModel.indicatorDataList[index]
                        item.display = index == position
                    }
                    indicatorAdapter.notifyDataSetChanged()

                    // 更新当前显示
                    if (permissionViewModel.indicatorDataList.size > position) {
                        val permission = permissionViewModel.indicatorDataList[position].permission
                        permissionViewModel.displayPermission = permission
                        updateDisplayPermission(permission)
                    }
                }

                override fun onPageScrollStateChanged(state: Int) {
                }
            })
        viewPager.adapter = pageAdapter

        // 询问弹框
        askDialog = PermissionGhanaAskDialog(object : IPermissionGhanaAskDialogListener {
            override fun onClick(type: Int) {
                if (0 == type) {
                    permissionViewModel.updateCheckbox()
                    binding.agree.performClick()
                }
            }
        })

        // 页面loading状态接口监听
        permissionViewModel.loadingResult.observe(this@PermissionGhanaSplashActivity, Observer {
            val loadingResult = it ?: return@Observer

            if (loadingResult) {
                loading.visibility = View.VISIBLE
            } else {
                loading.visibility = View.GONE
            }
        })

        // 页面checkbox状态监听
        permissionViewModel.checkResult.observe(this@PermissionGhanaSplashActivity, Observer {
            val checkResult = it ?: return@Observer

            if (checkResult) {
                checkbox.setImageResource(R.drawable.pic_permission_checkbox_hl)
            } else {
                checkbox.setImageResource(R.drawable.pic_permission_checkbox_nor)
            }
        })

        // 权限同意与否监听
        permissionViewModel.grantedResult.observe(
            this@PermissionGhanaSplashActivity,
            Observer {
                val grantedResult = it ?: return@Observer

                loading.visibility = View.GONE
                if (grantedResult.error != null) {
                    showMessage(grantedResult.error)
                }

                if (grantedResult.ask) {
                    askDialog.showNow(supportFragmentManager, "permissions")
                }

                if (grantedResult.start) {
                    askPermission(grantedResult.permission)
                }

                if (grantedResult.agree) {
                    for (index in 0 until permissionViewModel.indicatorDataList.size) {
                        val item = permissionViewModel.indicatorDataList[index]
                        if (item.permission.contains(grantedResult.permission, true)) {
                            item.optResult =
                                OPT_SPLASH_RESULT_AGREE
                        }
                    }
                    updateDisplayPermission(grantedResult.permission)
                }

                if (grantedResult.reject) {
                    for (index in 0 until permissionViewModel.indicatorDataList.size) {
                        val item = permissionViewModel.indicatorDataList[index]
                        if (item.permission.contains(grantedResult.permission, true)) {
                            item.optResult =
                                OPT_SPLASH_RESULT_REJECT
                        }
                    }
                    updateDisplayPermission(grantedResult.permission)
                }

                if (grantedResult.nextIndicator != null) {
                    viewPager.currentItem = grantedResult.nextIndicator
                }
            })

        // 流程接口监听
        permissionViewModel.mainProcessResult.observe(
            this@PermissionGhanaSplashActivity,
            Observer {
                val mainProcessResult = it ?: return@Observer

                loading.visibility = View.GONE
                if (mainProcessResult.error != null) {
                    showMessage(mainProcessResult.error)
                }

                if (mainProcessResult.success != null) {
                    permissionViewModel.nextRouter(mainProcessResult.success)
                }
            })

        // 页面需要跳转监听
        permissionViewModel.nextRouterResult.observe(this@PermissionGhanaSplashActivity, Observer {
            val nextRouterResult = it ?: return@Observer

            loading.visibility = View.GONE
            startNextActivity(
                activity = nextRouterResult.nextPage,
                permissionFlow = nextRouterResult.permissionFlow
            )
        })


        // 点击申请
        back.setOnClickListener {
            finish()
        }

        // 点击客服
        hotline.setOnClickListener {
            // 客服弹框
            HotlineGhanaDialog().showNow(supportFragmentManager, "hotline")
            hitPoint("SHOW_HOTLINE")
        }

        // 点击checkbox
        checkbox.setOnClickListener {
            permissionViewModel.updateCheckbox()
        }

        // 点击同意
        binding.agree.setOnClickListener {
            permissionViewModel.startPermissionGranted()
            hitPoint("PREMISSION_AGREE_CLICK", permissionViewModel.displayPermission)
        }

        // 点击拒绝
        binding.reject.setOnClickListener {
            permissionViewModel.grantedResult(false)
            hitPoint("PREMISSION_REJECT_CLICK", permissionViewModel.displayPermission)
        }

        // 更新权限列表
        permissionViewModel.pagerDataList.clear()
        permissionViewModel.indicatorDataList.clear()
        val perList = mutableListOf<String>().apply {
            addAll(ProjectApplication.mSplashPermissions)
        }
        for (index in 0 until perList.size) {
            val item = perList[index]
            val granted = checkPermissionsGranted(mutableListOf(item))
            if (!granted) {
                val pager = PermissionGhanaSplashPager(
                    permission = item,
                    optResult = OPT_SPLASH_RESULT_NONE,
                    display = false
                )
                permissionViewModel.pagerDataList.add(pager)
                permissionViewModel.indicatorDataList.add(pager)
            }
        }
        if (permissionViewModel.indicatorDataList.isNotEmpty()) {
            val pager = PermissionGhanaSplashPager(
                permission = PERMISSION_SPLASH_APP,
                optResult = OPT_SPLASH_RESULT_NONE,
                display = true
            )
            permissionViewModel.pagerDataList.add(0, pager)
            permissionViewModel.indicatorDataList.add(0, pager)
        }

        // 更新显示
        binding.index.text = "1/${permissionViewModel.indicatorDataList.size}"
        indicatorAdapter.notifyDataSetChanged()
        pageAdapter.notifyDataSetChanged()
    }

    /**
     * 更新当前权限显示
     */
    @SuppressLint("SetTextI18n")
    private fun updateDisplayPermission(checkPermission: String) {
        var item: PermissionGhanaSplashPager? = null
        var position = -1
        for (index in 0 until permissionViewModel.indicatorDataList.size) {
            val data = permissionViewModel.indicatorDataList[index]
            if (data.permission.contains(checkPermission, true)) {
                item = data
                position = index
                break
            }
        }
        if (item == null) return

        // 更新页码
        binding.index.text = "${(position + 1)}/${permissionViewModel.indicatorDataList.size}"

        // 记录当前权限
        val permission = item.permission
        if (permission.contains(PERMISSION_SPLASH_SMS, true)) {
            permissionViewModel.displayPermission =
                android.Manifest.permission.READ_SMS
            binding.type.text = "SMS Data Collection"
            binding.typeIcon.setImageResource(R.drawable.pic_permission_sms)

        } else if (permission.contains(PERMISSION_SPLASH_PHONE, true)) {
            permissionViewModel.displayPermission =
                android.Manifest.permission.READ_PHONE_STATE
            binding.type.text = "COLLECTION OF DEVICE INFO"
            binding.typeIcon.setImageResource(R.drawable.pic_permission_phone)

        } else {
            permissionViewModel.displayPermission =
                PERMISSION_SPLASH_APP
            binding.type.text = "COLLECTION OF DEVICE APP LIST DATA"
            binding.typeIcon.setImageResource(R.drawable.pic_permission_applist)
        }

        // 更新底部显示
        when (item.optResult) {
            OPT_SPLASH_RESULT_AGREE -> {
                binding.unActionBg.visibility = View.GONE
                binding.bannedBg.visibility = View.GONE
                binding.authorizedBg.visibility = View.VISIBLE
            }

            OPT_SPLASH_RESULT_REJECT -> {
                binding.unActionBg.visibility = View.GONE
                binding.bannedBg.visibility = View.VISIBLE
                binding.authorizedBg.visibility = View.GONE
            }

            else -> {
                binding.unActionBg.visibility = View.VISIBLE
                binding.bannedBg.visibility = View.GONE
                binding.authorizedBg.visibility = View.GONE
            }
        }
    }

    /**
     * 请求权限
     */
    private fun askPermission(permission: String = permissionViewModel.displayPermission): Boolean {
        if (permission.isNotBlank()) {
            val list = mutableListOf(permission)
            EasyPermissions.requestPermissions(
                this,
                "App will request this Permission",
                100,
                *(list.toTypedArray())
            )
        }
        return true
    }

    /**
     * 检查权限是否同意
     */
    private fun checkPermissionsGranted(permissionList: List<String>): Boolean {
        val isNotAllGranted = permissionList.any {
            PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(this, it)
        }
        return !isNotAllGranted
    }

    // ------> EasyPermissions <------
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray,
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this)
    }

    override fun onRationaleAccepted(requestCode: Int) {
        askPermission()
    }

    override fun onRationaleDenied(requestCode: Int) {
    }

    override fun onPermissionsDenied(requestCode: Int, perms: List<String>) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            SettingsDialog.Builder(this).build().show()
        }
        if (100 == requestCode) {
            permissionViewModel.grantedResult(false)
        }
    }

    override fun onPermissionsGranted(requestCode: Int, perms: List<String>) {
        // 跳转下一个权限
        permissionViewModel.grantedResult(true)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == DEFAULT_SETTINGS_REQ_CODE) {
            askPermission()
        }
    }

    fun showMessage(message: String) {
        Toast.makeText(applicationContext, message, Toast.LENGTH_SHORT).show()
    }

    fun startNextActivity(
        activity: Class<out AppCompatActivity>? = null,
        params: HashMap<String, String> = HashMap(),
        permissionFlow: Boolean = false
    ) {
        val nextActivity = activity ?: return
        try {
            val intent = Intent(this, nextActivity)
            if (!permissionFlow) {
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_NEW_TASK)
            }
            params.keys.forEach { gKey ->
                intent.putExtra(gKey, params[gKey])
            }
            startActivity(intent)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun onResume() {
        super.onResume()
        hitPoint(type = this::class.java.simpleName, isPageStart = true)
    }

    override fun onPause() {
        super.onPause()
        hitPoint(type = this::class.java.simpleName, isPageEnd = true)
    }
}


/**
 * adapter
 */
class PermissionGhanaSplashIndicatorAdapter(
    private val dataList: List<PermissionGhanaSplashPager>
) :
    RecyclerView.Adapter<PermissionGhanaSplashIndicatorAdapter.ViewHolder>() {

    inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        private val dot: View = view.findViewById(R.id.dot)

        fun setItem(checked: Boolean) {
            if (checked) {
                dot.setBackgroundResource(R.drawable.bg_permission_indicator_selected)
            } else {
                dot.setBackgroundResource(R.drawable.bg_permission_indicator_unselect)
            }
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.view_ghana_permission_indicator_adapter, parent, false)
        // 重置宽度
        val itemWith = 24F.dpToPx()
        view.layoutParams.width = itemWith.toInt()
        return ViewHolder(view)
    }

    @SuppressLint("SetTextI18n")
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val item: PermissionGhanaSplashPager = dataList[position]
        holder.setItem(item.display)
    }

    override fun getItemCount(): Int {
        return dataList.size
    }

    // 将 dp 转换为像素
    private fun Float.dpToPx(): Float {
        return this * ProjectApplication.instance.resources.displayMetrics.density
    }
}

const val PERMISSION_SPLASH_APP = "APPLIST"
const val PERMISSION_SPLASH_SMS = "SMS"
const val PERMISSION_SPLASH_PHONE = "PHONE"

const val OPT_SPLASH_RESULT_AGREE = 0
const val OPT_SPLASH_RESULT_REJECT = 1
const val OPT_SPLASH_RESULT_NONE = 2

data class PermissionGhanaSplashPager(
    var permission: String = PERMISSION_SPLASH_APP,
    var optResult: Int = OPT_SPLASH_RESULT_NONE,
    var display: Boolean = false
)

class PermissionGhanaSplashPageAdapter(
    val context: Context,
    val dataList: List<PermissionGhanaSplashPager>
) : PagerAdapter() {

    override fun instantiateItem(container: ViewGroup, position: Int): Any {
        val item = dataList[position]
        var view: View = View.inflate(context, R.layout.view_ghana_permission_app, null)

        if (item.permission.contains(PERMISSION_SPLASH_SMS, true)) {
            view = View.inflate(context, R.layout.view_ghana_permission_sms, null)
        }
        if (item.permission.contains(PERMISSION_SPLASH_PHONE, true)) {
            view = View.inflate(context, R.layout.view_ghana_permission_phone, null)
        }
        container.addView(view)
        return view
    }

    override fun getItemPosition(obj: Any): Int {
        return POSITION_NONE;
    }

    override fun getCount(): Int {
        return dataList.size
    }

    override fun isViewFromObject(view: View, `object`: Any): Boolean {
        return view === `object`
    }

    override fun destroyItem(container: ViewGroup, position: Int, obj: Any) {
        container.removeView(obj as View)
    }
}


